﻿using StudentManagement.DAL;
using StudentManagement.Entities;
using System;
using System.Collections.Generic;

namespace StudentManagement.BO
{
    public class TbcUserBO
    {
        private readonly TbcUserDAL _userDAL;

        public TbcUserBO(string connectionString)
        {
            _userDAL = new TbcUserDAL(connectionString);
        }

        /// <summary>
        /// 根据ID获取用户
        /// </summary>
        public TbcUserInfo GetUserById(int userId)
        {
            if (userId <= 0)
                throw new ArgumentException("用户ID必须大于0");

            return _userDAL.GetById(userId);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        public int AddUser(TbcUserInfo user)
        {
            ValidateUser(user);
            return _userDAL.Add(user);
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        public bool UpdateUser(TbcUserInfo user)
        {
            if (user.TbcUserID <= 0)
                throw new ArgumentException("用户ID无效");

            ValidateUser(user);
            return _userDAL.Update(user);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        public bool DeleteUser(int userId)
        {
            if (userId <= 0)
                throw new ArgumentException("用户ID必须大于0");

            return _userDAL.Delete(userId);
        }

        /// <summary>
        /// 分页查询用户
        /// </summary>
        public (List<TbcUserInfo> Data, int TotalCount) GetPagedUsers(string keyword, int pageIndex, int pageSize)
        {
            if (pageIndex <= 0) pageIndex = 1;
            if (pageSize <= 0) pageSize = 10;
            if (pageSize > 100) pageSize = 100; // 限制每页最大数量

            return _userDAL.GetPagedList(keyword, pageIndex, pageSize);
        }

        /// <summary>
        /// 验证用户信息
        /// </summary>
        private void ValidateUser(TbcUserInfo user)
        {
            if (string.IsNullOrWhiteSpace(user.TbcUserName))
                throw new ArgumentException("用户名不能为空");

            if (string.IsNullOrWhiteSpace(user.TbcPassword))
                throw new ArgumentException("密码不能为空");

            if (user.TbcUserName.Length > 20)
                throw new ArgumentException("用户名长度不能超过20个字符");

            if (user.TbcPassword.Length > 50)
                throw new ArgumentException("密码长度不能超过50个字符");
        }
    }
}